<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="封面图" prop="cover">
        <UploadImg v-model="formData.cover"/>
      </el-form-item>
      <el-form-item label="父ID" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="categoryTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择父ID"
          @change="handleParentIdChange"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <UploadImg v-if="formData.type==='MIDDLE'" v-model="formData.icon"/>
        <el-input v-else v-model="formData.icon" placeholder="请输入图标,参考element2.0" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MZT_CATEGORY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推荐" prop="recommend"
                    v-if="formData.categoryType!=='button' && formData.type === 'TOP'">
        <el-radio-group v-model="formData.recommend">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.MZT_RECOMMEND)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="事件" prop="event" v-if="formData.categoryType==='button'">
        <el-select v-model="formData.event" placeholder="请选择类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MZT_CATEGORY_EVENT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="路由地址" prop="path">
        <el-input v-model="formData.path" placeholder="请输入路由地址"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.MZT_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="按钮类型" prop="categoryType" v-if="formData.type == 'TOP'">
        <el-radio-group v-model="formData.categoryType">
          <el-radio-button
            v-for="dict in getStrDictOptions(DICT_TYPE.MZT_CATEGORY_CATEGORY_TYPE)"
            :key="dict.label"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" controls-position="right"/>
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入描述"/>
      </el-form-item>
      <el-form-item label="SEO标题" prop="seoTitle"
                    v-if="formData.type ==='TOP' && formData.categoryType!=='button'">
        <el-input v-model="formData.seoTitle" type="textarea" placeholder="请输入SEO标题"/>
      </el-form-item>
      <el-form-item label="SEO关键词" prop="seoKeywords"
                    v-if="formData.type ==='TOP' && formData.categoryType!=='button'">
        <el-input v-model="formData.seoKeywords" type="textarea" placeholder="请输入SEO关键词"/>
      </el-form-item>
      <el-form-item label="SEO描述" prop="seoDescription"
                    v-if="formData.type ==='TOP' && formData.categoryType!=='button'">
        <el-input v-model="formData.seoDescription" type="textarea" placeholder="请输入SEO描述"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getIntDictOptions, getStrDictOptions, DICT_TYPE} from '@/utils/dict'
import {CategoryApi, CategoryVO} from '@/api/mzt/category'
import {defaultProps, handleTree} from '@/utils/tree'

/** 分类 表单 */
defineOptions({name: 'CategoryForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  parentId: undefined,
  name: undefined,
  type: undefined,
  icon: undefined,
  cover: undefined,
  status: 0,
  path: undefined,
  recommend: 0,
  sort: 0,
  event: undefined,
  remark: undefined,
  seoTitle: undefined,
  seoKeywords: undefined,
  seoDescription: undefined,
  level: 0,
  categoryType: 'button',
})
const formRules = reactive({
  parentId: [{required: true, message: '父ID不能为空', trigger: 'blur'}],
  name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  type: [{required: true, message: '类型不能为空', trigger: 'change'}],
  status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
  recommend: [{required: true, message: '推荐不能为空', trigger: 'blur'}],
  sort: [{required: true, message: '排序不能为空', trigger: 'blur'}],
  event: [{required: true, message: '事件不能为空', trigger: 'blur'}],
  categoryType: [{required: true, message: '分类按钮类型不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref
const categoryTree = ref() // 树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  await getCategoryTree()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CategoryApi.getCategory(id)
      formData.value.level = getLevelById(formData.value.parentId)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 检查层级
  if (formData.value.level > 4) {
    message.error('最多只能选择三级菜单')
    return
  }
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {...formData.value, level: formData.value.level} as unknown as CategoryVO
    if (formType.value === 'create') {
      await CategoryApi.createCategory(data)
      message.success(t('common.createSuccess'))
    } else {
      await CategoryApi.updateCategory(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    parentId: undefined,
    name: undefined,
    type: undefined,
    icon: undefined,
    cover: undefined,
    status: 0,
    path: undefined,
    recommend: 0,
    sort: 0,
    event: undefined,
    remark: undefined,
    seoTitle: undefined,
    seoKeywords: undefined,
    seoDescription: undefined,
    level: 0,
    categoryType: 'button',
  }
  formRef.value?.resetFields()
}

/** 获得分类树 */
const getCategoryTree = async () => {
  categoryTree.value = []
  const data = await CategoryApi.getCategoryList()
  const root: Tree = {id: 0, name: '顶级分类', children: []}
  root.children = handleTree(data, 'id', 'parentId')
  categoryTree.value.push(root)
}

// 新增函数：根据父ID获取层级
const getLevelById = (parentId) => {
  let level = 0
  const findLevel = (tree, id, currentLevel) => {
    for (const node of tree) {
      if (node.id === id) {
        level = currentLevel
        return true
      }
      if (node.children) {
        if (findLevel(node.children, id, currentLevel + 1)) {
          return true
        }
      }
    }
    return false
  }
  findLevel(categoryTree.value, parentId, 1)
  return level
}

// 在 el-tree-select 中限制选择的层级
const handleParentIdChange = (value) => {
  const selectedLevel = getLevelById(value)
  if (selectedLevel > 4) {
    message.error('不能选择超过三级菜单')
    formData.value.parentId = undefined // 清空选择
  } else {
    formData.value.level = selectedLevel // 更新层级
  }
}
</script>
